package com.itheima.utils;

import com.aliyun.tea.*;
import com.aliyun.dysmsapi20170525.*;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.*;
import com.aliyun.teaopenapi.models.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class SmsUtil {

    public static final String CONFIG_ENDPOINT = "dysmsapi.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    public static final String ACCESS_KEY_ID = "LTAI5t9HgytbMkHwDzo1j7HP";
    public static final String ACCESS_KEY_SECRET = "pkRnog0AVhhrlWxAMT5yi9AQweRz2M";

    //短信签名
    public static final String SING_NAME = "传智健康";

    //短信模板
    public static final String TEMPLATE_CODE = "SMS_201652315";

    //短信验证码位数
    public static final Integer SMS_NUM = 6;

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = CONFIG_ENDPOINT;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static String sendSms(String telephone) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        Map<String,String> codeMap = new HashMap<>();
        String code = RandomStringUtils.randomNumeric(SMS_NUM);
        //随机生成指定位数的字符串
        codeMap.put("code", code);
        ObjectMapper objectMapper = new ObjectMapper();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(telephone)
                .setSignName(SING_NAME)
                .setTemplateCode(TEMPLATE_CODE)
                .setTemplateParam(objectMapper.writeValueAsString(codeMap));
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        if("OK".equals(sendSmsResponse.body.code))
            return code;
        return null;
    }

    //如果短信验证不通过，则可以简单用这个东西替代，随机生成的验证码
    public static String sendSmsCode() throws Exception {
        return RandomStringUtils.randomNumeric(SMS_NUM);
    }

}
